package com.youlai.netty.service.tcp.server;

import com.youlai.netty.service.handler.UDPHandler;
import com.youlai.netty.service.tcp.BootNettyChannelInboundHandlerAdapter;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author zc
 * @date 2023-02-04 18:47
 */
@Slf4j
public class UDPServer {
    public void bind(int port){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) {
                                   ch.pipeline().addLast(new NioEventLoopGroup(),new UDPHandler());
                        }
                    });
        try {
            ChannelFuture f = bootstrap.bind(port).sync();
            if(f.isSuccess()){
                log.info("udp服务启动成功,端口:{}",port);
                /**
                 * 等待服务器监听端口关闭
                 */
                try {
                    f.channel().closeFuture().sync();
                }catch (InterruptedException e){
                    log.warn("udp服务关闭异常:{}",e.getMessage());
                }finally {
                    group.shutdownGracefully();
                }
            }else{
                bootstrap.config().group().schedule(() -> bind(port),5, TimeUnit.SECONDS);
                log.error("创建udp服务失败:{}",f.cause().getMessage());
            }
        } catch (InterruptedException e) {
            log.warn("udp服务启动异常:{}",e.getMessage());
        }
    }
}
